package com.hxkcloud.nurse.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.hxkcloud.nurse.ActivityManager;
import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.YjhApplication;
import com.hxkcloud.nurse.alarm.Alarm;
import com.hxkcloud.nurse.alarm.Alarms;
import com.hxkcloud.nurse.beans.AddressBean;
import com.hxkcloud.nurse.beans.ArticleKindBean;
import com.hxkcloud.nurse.beans.LoginInfo;
import com.hxkcloud.nurse.beans.MonitorKindBean;
import com.hxkcloud.nurse.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.nurse.dborm.AddressDao;
import com.hxkcloud.nurse.dborm.ArticleKindDao;
import com.hxkcloud.nurse.dborm.LoginInfoDao;
import com.hxkcloud.nurse.dborm.MonitorKindDao;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.ImageUtil;
import com.hxkcloud.nurse.utils.SharedPreferenceUtil;
import com.hxkcloud.nurse.utils.StringUtil;
import com.hxkcloud.nurse.views.MyToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by william_sun on 2016-07-05.
 * Description:登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_whole;
    private ImageView iv_logo;
    private ImageView iv_phone;
    private EditText et_phone;
    private ImageView iv_password;
    private EditText et_password;
    private TextView tv_forgetpw;
    private Button bt_login;
    private Button bt_register;

    private List<ArticleKindBean> kinds_news;
    private List<ArticleKindBean> kinds_course;
    private int needPrepareNum = 0;//需要获取的基础数据数

    private boolean phoneInput = false;//记录手机号码输入框是否输入
    private boolean passwordInput = false;//记录密码框是否输入

    private ObjectResultBean<LoginInfo> resultBean;

    private String account = "";
    private String password = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private long saveAlarm(long date, long time, int mHour, int mMinutes) {
        Alarm alarm = new Alarm();
        alarm.enabled = true;
        alarm.hour = mHour;
        alarm.minutes = mMinutes;
        alarm.isDelay = false;
        alarm.date = date + "";
        alarm.time = time + "";

        long timee = 0;
        timee = Alarms.addAlarm(this, alarm);
        return timee;
    }

    private void delAlarms() {
        Alarms.clearAlarm(this);
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_SUBMITLOGIN_SUCCESS:
                if (msg.obj != null) {

                    resultBean = (ObjectResultBean<LoginInfo>) msg.obj;
                    if (resultBean.getData() == null) {
                        toastMsg(getResources().getString(R.string.loginfail));
                        return;
                    }
                    toastMsg(resultBean.getMessage());

                    //保存数据库
                    loginInfo = resultBean.getData();
                    loginInfo.setDepartmentId(loginInfo.getDepartmentId());
                    LoginInfoDao userDao = new LoginInfoDao(mContext);
                    if (!TextUtils.isEmpty(loginInfo.getAddressId())) {
                        try {
                            String address = "";
                            String addressId = loginInfo.getAddressId();
                            AddressDao addressDao = new AddressDao(mContext);
                            AddressBean area = addressDao.getOneAddress(addressId);
                            AddressBean city = addressDao.getOneAddress(area.getParrentId());
                            AddressBean province = addressDao.getOneAddress(city.getParrentId());
                            address = province.getName() + city.getName() + area.getName();
                            loginInfo.setAddress(address);
                        } catch (Exception e) {
                        }
                    }
                    userDao.setUser(loginInfo);
                    if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {
                        emClientLogin();
                        JPushInterface.setAlias(mContext, account, null);
                        SharedPreferenceUtil.setIsrunning(mContext, true);
                        SharedPreferenceUtil.setLoginAccount(mContext, account);
                        SharedPreferenceUtil.setLoginPassword(mContext, password);
                        //zhugeio
                        try {
                            JSONObject personObject = new JSONObject();
                            personObject.put("name", loginInfo.getName());
                            personObject.put("phone", account);
                        } catch (JSONException e) {
                        }
                        Intent iNurseMain = new Intent(mContext, NurseFragmentActivity.class);
                        iNurseMain.putExtra("getbasic", true);
                        startActivity(iNurseMain);
                        finish();
                    } else {
                        toastMsg("无此账户!");
                    } /*else if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
                     *//*   Intent iPatientMain = new Intent(mContext, UserFragmentActivity.class);
                        iPatientMain.putExtra("getbasic", true);
                        startActivity(iPatientMain);
                        finish();*//*
                        toastMsg("无此账户!");
                        return;
                    } else if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_doctor)) {
                        Intent iDoctorMain = new Intent(mContext, DoctorFragmentActivity.class);
                        iDoctorMain.putExtra("getbasic", true);
                        startActivity(iDoctorMain);

                    }*/


                }

                break;
            case MessageCode.NETWORKCODE_SUBMITLOGIN_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.loginfail));
                }

                break;
            case MessageCode.NETWORKCODE_MONITORKIND_SUCCESS:
                List<MonitorKindBean> kinds = (List<MonitorKindBean>) msg.obj;
                if (kinds != null && kinds.size() > 0) {
                    MonitorKindDao monitorKindDao = new MonitorKindDao(mContext);
                    monitorKindDao.setKind(kinds, "1");
                    toMain();
                }
                break;
            case MessageCode.NETWORKCODE_MONITORKIND_FAILURE:
                toMain();
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS0:
                kinds_news = (List<ArticleKindBean>) msg.obj;
                if (kinds_course != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, "1");
                    toMain();
                }
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_SUCCESS1:
                kinds_course = (List<ArticleKindBean>) msg.obj;
                if (kinds_news != null) {
                    ArticleKindDao kindDao = new ArticleKindDao(mContext);
                    kindDao.setKind(kinds_news, kinds_course, "1");
                    toMain();
                }
                break;
            case MessageCode.NETWORKCODE_ARTICLEKINDLIST_FAILURE:
                toMain();
                break;

        }

    }

    //环信登录
    private void emClientLogin() {
        EMClient.getInstance().login("ejh" + account, "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                //以下两个方法是为了保证进入主页面后本地会话和群组都 load 完毕
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();
                Log.e("EASE", "loginSuccess");
            }

            @Override
            public void onError(int i, String s) {
                Log.e("EASE", "登录聊天服务器失败！" + s);
                if (i == 204) {//不存在此用户
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                EMClient.getInstance().createAccount("ejh" + account, "123456");
                                emClientLogin();
                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                Log.e("EASE", e.toString());
                            }
                        }
                    }.start();
                }
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

    }

    private void toMain() {
        needPrepareNum--;
        if (needPrepareNum == 0) {
            if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {
                Intent iNurseMain = new Intent(mContext, NurseFragmentActivity.class);
                startActivity(iNurseMain);
                finish();
            }else {
                toastMsg("无此账户!");
            } /*else if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_patient)) {
                toastMsg("无此账户!");
            *//*    Intent iPatientMain = new Intent(mContext, UserFragmentActivity.class);
                startActivity(iPatientMain);
                finish();*//*
            } else if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_doctor)) {
                Intent iDoctorMain = new Intent(mContext, DoctorFragmentActivity.class);
                startActivity(iDoctorMain);
                finish();
            }*/
        }
    }

    @Override
    protected void initView() {
        ll_whole = (LinearLayout) findViewById(R.id.ll_login);
        iv_logo = (ImageView) findViewById(R.id.iv_login_logo);
        iv_phone = (ImageView) findViewById(R.id.iv_login_phone);
        et_phone = (EditText) findViewById(R.id.et_login_phone);
        iv_password = (ImageView) findViewById(R.id.iv_login_pw);
        et_password = (EditText) findViewById(R.id.et_login_password);
        tv_forgetpw = (TextView) findViewById(R.id.tv_login_forgetpw);
        bt_login = (Button) findViewById(R.id.bt_login_login);
        bt_register = (Button) findViewById(R.id.bt_login_register);

        setTitlePadding(ll_whole);
        LinearLayout.LayoutParams lp_logo = new LinearLayout.LayoutParams((screenWidth / 4) + 40, (screenWidth / 4) + 30);
        lp_logo.leftMargin = ImageUtil.dip2px(5, this);
        iv_logo.setLayoutParams(lp_logo);
        LinearLayout.LayoutParams lp_phone = new LinearLayout.LayoutParams(screenWidth / 16, screenWidth / 16);
        lp_phone.rightMargin = ImageUtil.dip2px(30, this);
        iv_phone.setLayoutParams(lp_phone);
        iv_password.setLayoutParams(lp_phone);
        bt_login.setEnabled(false);

        tv_forgetpw.setOnClickListener(this);
        bt_login.setOnClickListener(this);
        bt_register.setOnClickListener(this);

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    phoneInput = false;
                    bt_login.setBackgroundResource(R.drawable.bt_grey);
                    bt_login.setEnabled(false);
                } else {
                    phoneInput = true;
                    if (passwordInput) {
                        bt_login.setBackgroundResource(R.drawable.bt_blue);
                        bt_login.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    passwordInput = false;
                    bt_login.setBackgroundResource(R.drawable.bt_grey);
                    bt_login.setEnabled(false);
                } else {
                    passwordInput = true;
                    if (phoneInput) {
                        bt_login.setBackgroundResource(R.drawable.bt_blue);
                        bt_login.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_phone.setText(SharedPreferenceUtil.getLoginAccount(mContext));
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login_forgetpw:
                Intent iFindPw = new Intent(mContext, FindPasswordActivity.class);
                startActivity(iFindPw);
                break;
            case R.id.bt_login_login:
                StringUtil.zhugeTrack(mContext, "登录", "登录按钮点击数");
                account = et_phone.getText().toString().trim();
                password = et_password.getText().toString().trim();
                loading();
                YiJiaHuNetWorkUtils.submitLogin(account, password, handler);
                break;
            case R.id.bt_login_register:
                Intent iRegister = new Intent(mContext, RegisterPhoneActivity.class);
                startActivity(iRegister);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {

            MyToast.geToast().cancel();
            SharedPreferenceUtil.setIsrunning(mContext, false);
//                MobclickAgent.onKillProcess(this);

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    finish();
                    ActivityManager.getInstance().removeAllActivity();
                    System.exit(0);
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }, 100);
            // finish();
            // System.exit(0);

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
